<?php

namespace App\Listeners;

use App\Helpers\LogHelper;
use DateTime;
use Exception;
use Illuminate\Database\Events\QueryExecuted;

class QueryListener
{
    const MARK = 'sql_log';

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param QueryExecuted $event
     */
    public function handle(QueryExecuted $event)
    {
        // 日志打开或者特殊的记录日志的账号
        if (env("APP_LOG_OPEN", false))
        {

            // 此处处理异常 避免阻断主流程
            try
            {
                $this->writeLog($event);
            } catch (Exception $ex)
            {
                $errInfo = [
                    'errMsg' => $ex->getMessage(),
                    "logId"  => NEO_LOGGER_ID,
                ];
                // 获取日志路径
                LogHelper::info(self::MARK,  $errInfo);
            }
        }
    }

    /**
     * 写日志
     *
     * @param QueryExecuted $event
     */
    protected function writeLog(QueryExecuted $event)
    {
        foreach ($event->bindings as $i => $binding)
        {
            if ($binding instanceof DateTime)
            {
                $event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
            }
            else
            {
                if (is_string($binding))
                {
                    $event->bindings[$i] = "'$binding'";
                }
            }
        }

        // 获取日志路径
        $info = [
            "runtime"   => $event->time . "ms",    // sql执行时间
            "sql"       => $event->sql,            // sql语句
            "sqlParams" => $event->bindings,    // sql参数： 需要替换对应的 ？
            "logId"     => NEO_LOGGER_ID,        // logId  多文件，多日志，可以用此id匹配表示同一个进程生产的
        ];

        LogHelper::info(self::MARK,  $info);
    }
}
